package com.jby.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jby.seckill.exception.GlobalException;
import com.jby.seckill.mapper.OrderMapper;
import com.jby.seckill.pojo.Order;
import com.jby.seckill.pojo.SeckillGoods;
import com.jby.seckill.pojo.SeckillOrder;
import com.jby.seckill.pojo.User;
import com.jby.seckill.service.IGoodsService;
import com.jby.seckill.service.IOrderService;
import com.jby.seckill.service.ISeckillGoodsService;
import com.jby.seckill.service.ISeckillOrderService;
import com.jby.seckill.vo.GoodsVo;
import com.jby.seckill.vo.OrderDetailVo;
import com.jby.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiangbaiyu
 * @since 2021-12-19
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ISeckillGoodsService seckillGoodsService;


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ISeckillOrderService seckillOrderService;

    @Autowired
    private IGoodsService goodsService;

    @Override
    public Order seckill(User user, GoodsVo goodsVo) {

        //秒杀商品扣减库存
        SeckillGoods seckillGoods = seckillGoodsService.getOne(new QueryWrapper<SeckillGoods>()
                .eq("goods_id",goodsVo.getId()));
        seckillGoods.setStockCount(seckillGoods.getStockCount()-1);
        seckillGoodsService.updateById(seckillGoods);
        //生成订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goodsVo.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goodsVo.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateTime(new Date());
        orderMapper.insert(order);

        //生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(user.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setGoodsId(goodsVo.getId());
        seckillOrderService.save(seckillOrder);

        return order;


    }

    @Override
    public OrderDetailVo detail(Long orderId) {
        if (orderId == null) {
            throw new GlobalException(RespBeanEnum.ORDER_NOT_EXIST);
        }
        //根据订单id查出订单
        Order order = orderMapper.selectById(orderId);
        //通过订单中的商品id查出商品的详情返回对象
        GoodsVo goodsVo = goodsService.findGoodsVoById(order.getGoodsId());

        OrderDetailVo detail = new OrderDetailVo();
        detail.setOrder(order);
        detail.setGoodsVo(goodsVo);
        return detail;
    }
}
